<template>
  <div>
    <div v-for="(item, index) in contractData" :key="index">
      <p class="titleStyle">{{ item.info.itemText }}</p>
      <div class="parentBox">
        <div
          v-for="(item1, index) in item.data"
          :key="index"
          class="itemBox"
          @mouseover="getShow(index)"
          @mouseleave="getOff(index)"
        >
          <div class="item1box1">
            <img :src="item1.fileIconSrc" alt="" />
            <span class="item1span">{{ item1.name }}</span>
          </div>

          <img :src="item1.showImgSrc" alt="" class="item1Img" />
          <div class="buttombox">
            <span>{{ item.info.itemText }}</span>
            <el-popconfirm
              class="deleteButton"
              cancel-button-text
              title="确定删除此合同吗？"
              @onConfirm="deleteImg(item1.id)"
            >
              <el-button
                v-if="deleteFile"
                class="imgDeletes"
                slot="reference"
                size="small"
                v-no-more-click
              ></el-button>
            </el-popconfirm>
            <!-- <img class="imgDelete" src="../../assets/img/删除 (1).png" alt="" @click="deleteImg(item1.id)"> -->
          </div>
          <div class="maskBox" v-if="maskStyle == index">
            <!-- v-if="maskStyle" -->
            <div class="box1">
              <el-button
                class="buttonClass"
                type="danger"
                @click="downloadEvent(item1.name, item1.url)"
              >立即下载
              </el-button
              >
            </div>
            <div class="box2">
              <el-button class="buttonClass" @click="viewEvent(item1.url)"
              >查 看
              </el-button
              >
            </div>
          </div>
        </div>
        <div
          class="itemBox uplodItem"
          @click="dialog(item.info.itemValue)"
          v-if="UplodFile"
        >
          <img
            src="../../assets/img/文档上传@2x.png"
            alt=""
            class="itemBoxImg"
          />

          <div class="indexUplog">上传合同</div>
        </div>
      </div>
    </div>
    <el-dialog
      title="上传合同:"
      :visible.sync="dialogVisible"
      width="22%"
      :before-close="handleClose"
    >
      <el-row>
        <el-form :inline="true" style="text-align: left">
          <el-col :span="24">
            <el-form-item label="模板名称:">
              <el-input v-model="form.name"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="合同类型:">
              <el-select v-model="form.contractType" placeholder="请选择">
                <el-option
                  v-for="item in contractTypeArray"
                  :key="item.itemValue"
                  :label="item.itemText"
                  :value="item.itemValue"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="文件类型:">
              <el-select v-model="form.fileType" placeholder="请选择">
                <el-option
                  v-for="item in fileTypeArray"
                  :key="item.itemValue"
                  :label="item.itemText"
                  :value="item.itemValue"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item>
              <el-upload
                class="upload-demo"
                action=""
                ref="uploadImg"
                :multiple="false"
                accept=""
                list-type="picture"
                :http-request="upload"
                :on-remove="imgHandlerRemove"
                :on-change="imgHandlerChange"
              >
                <el-button size="small" type="primary"
                >点击上传文件封面
                </el-button
                >
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item>
              <el-upload
                accept=".pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx"
                class="upload-demo"
                action=""
                ref="uploadFile"
                :multiple="false"
                :http-request="upload"
                :on-remove="fileHandlerRemove"
                :on-change="fileHandlerChange"
              >
                <el-button size="small" type="primary"
                >点击上传合同文档
                </el-button
                >
              </el-upload>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <el-button type="primary" @click="submitData">提交</el-button>
      <el-button @click="cancelUplod">取消</el-button>
      <span slot="footer" class="dialog-footer">
        <!-- <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialog">确 定</el-button> -->
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  getcontractModel,
  getPermType,
  submitCode,
  uploadContract,
  contractDelete
} from "../../assets/js/api";
import { checkPermiss } from "../../assets/js/utlis";

export default {
  data() {
    return {
      contractData: [], //合同模板数据列表数组!
      maskStyle: null, //赫兹遮罩层开关!
      url: "",
      stsdata: null,
      dialogVisible: false,
      uplodType: "", //上传文件类型!
      fileTypeArray: [], //文件类型数组!
      contractTypeArray: [], //合同类型数组!
      imgParam: null,
      fileParam: null,
      config: {
        headers: {
          "Content-Type": "multipart/form-data"
        }
      },
      form: {
        name: "", //模板名称!
        contractType: "", //合同类型!
        fileType: "", //文件类型!
        showImgSrc: "",
        url: ""
      },
      imgFileList: [],
      fileList: [],
      fileForm: {},
      formData: {},
      ossUrl: ""
    };
  },
  computed: {
    //附件查看
    UplodFile: function() {
      return checkPermiss("business:contract:upload", this.golbalPermissions);
    },
    //附件删除
    deleteFile: function() {
      return checkPermiss("business:contract:delete", this.golbalPermissions);
    }
  },
  created() {
    //获取合同模板列表!
    this.getData();
    this.golbalPermissions = localStorage.getItem("permissions").split(",");
  },
  methods: {
    // 图片上传移除的钩子!
    imgHandlerRemove(file, fileList) {
      this.imgFileList = fileList;
    },
    // 图片改变时的钩子!
    imgHandlerChange(file, fileList) {
      this.imgFileList = fileList;
    },
    upload() {
    },
    // 上传移除文件的钩子!
    fileHandlerRemove(file, fileList) {
      this.fileList = fileList;
    },
    // 上传文件改变时的钩子!
    fileHandlerChange(file, fileList) {
      this.fileList = fileList;
    },
    // 删除合同按钮!
    deleteImg(id) {
      contractDelete(id).then((res) => {
        if (res.code == 200) {
          this.$message.success(res.message);
          this.getData();
        } else {
          this.$message.error(res.message);
        }
      });
    },

    // 获取合同模板列表!
    getData() {
      getcontractModel().then((res) => {
        this.contractData = res.data;
      });
    },
    // 盒子遮罩层鼠标移上显示!
    getShow(index) {
      this.maskStyle = index;

      // this.maskStyle = true;
    },
    // 盒子遮罩层鼠标移上隐藏!
    getOff() {
      this.maskStyle = null;
    },
    // 查看按钮!
    viewEvent(data) {
      if (data == "") {
        this.$message({ message: "未上传合同文档", type: "error" });
        return;
      } else {
        console.log(data);
        window.open(
          "http://www.xdocin.com/xdoc?_func=to&_format=html&_cache=1&_xdoc=" +
            data
        );
        // window.open(
        //   "https://view.officeapps.live.com/op/view.aspx?src=" +
        //     data
        // );
        // window.open(
        //   "https://view.xdocin.com/view?src=" +
        //     data
        // );
      }
    },
    //上传按钮弹出层!
    dialog(data) {
      this.uplodType = data;
      this.dialogVisible = true;
      this.contractType();
      this.fileType();
    },
    //获取授权下载地址
    async getOssDownLoadUrl(oldurl, fileName) {
      let url = "";
      if (!this.stsdata) {
        //获取令牌
        await this.axios.get("/business/survey/getStsToken", {}).then((res) => {
          if (res) {
            this.stsdata = res.data.data;
          }
        });
      }
      //创建oss对象
      const OSS = require("ali-oss");
      const client = new OSS({
        // yourRegion填写Bucket所在地域。以华东1（杭州）为例，Region填写为oss-cn-hangzhou。
        region: "oss-cn-chengdu",
        // 从STS服务获取的临时访问密钥（AccessKey ID和AccessKey Secret）。
        accessKeyId: this.stsdata.accessKeyId,
        accessKeySecret: this.stsdata.accessKeySecret,
        // 从STS服务获取的安全令牌（SecurityToken）。
        stsToken: this.stsdata.securityToken,
        // 填写Bucket名称。
        bucket: "drxf-oss"
      });
      // 配置响应头实现通过URL访问时自动下载文件，并设置下载后的文件名。
      //const filename = fileName // 自定义下载后的文件名。
      const response = {
        "content-disposition": `attachment; filename=${encodeURIComponent(
          fileName
        )}`
      };
      // 填写Object完整路径。Object完整路径中不能包含Bucket名称。
      url = client.signatureUrl(oldurl.substring(oldurl.indexOf("static")), {
        response
      });
      return url;
    },
    /* async fileLinkToStreamDownload(url, fileName, type) {

      // let reg =
      //   /^([hH][tT]{2}[pP]:\/\/|[hH][tT]{2}[pP][sS]:\/\/)(([A-Za-z0-9-~]+).)+([A-Za-z0-9-~\/])+$/;
      // if (!reg.test(url)) {
      //   throw new Error("传入参数不合法,不是标准的文件链接");
      // } else {
      /* let xhr = new XMLHttpRequest();
      xhr.open("get", url, true);
 
      xhr.setRequestHeader("Content-Type", `application/${type}`);
      xhr.responseType = "blob";
      xhr.onload = function () {
       
        if (this.status == 200) {
          //接受二进制文件流

          var blob = this.response;
          const blobUrl = window.URL.createObjectURL(blob);
          // 这里的文件名根据实际情况从响应头或者url里获取
          const a = document.createElement("a");
          a.href = blobUrl;
          a.download = fileName;
          a.click();
          window.URL.revokeObjectURL(blobUrl);
        }
      };
      xhr.send(); 
      // }
    },*/
    // 下载按钮!
    async downloadEvent(name, url) {
      if (url == "") {
        this.$message({
          message: "当前合同还未上传文档,无法下载!",
          type: "error"
        });
        return;
      } else {
        let type = url.split(".");
        type = type[type.length - 1];
        let fileName = name + "." + type;
        url = await this.getOssDownLoadUrl(url, fileName);
        window.open(url, "_blank");
      }

      //this.fileLinkToStreamDownload(url, name, type);
    },
    // 文件类型数据查询!
    fileType() {
      getPermType("file_icon").then((res) => {
        this.fileTypeArray = res.data;
      });
    },
    //合同类型数据查询!
    contractType() {
      getPermType("contract_model_type").then((res) => {
        this.contractTypeArray = res.data;
      });
    },
    // 提交按钮!
    async uploadToOss(params, fieldName) {
      var dataOss = "";
      var suffix = "";
      await submitCode().then((res) => {
        let imgName = params.name;
        suffix = imgName.split(".");

        suffix = suffix[suffix.length - 1];
        let wz = imgName.split(".");
        let imgType = "." + wz[wz.length - 1];
        //创建文件
        let formData = new FormData();
        //上传对象
        dataOss = res.data;
        let ossUrl = dataOss.host;
        formData.append("policy", dataOss.policy);
        formData.append("key", dataOss.dir + dataOss.fileName + imgType);
        formData.append("OSSAccessKeyId", dataOss.accessid);
        formData.append("Signature", dataOss.signature);
        formData.append("success_action_status", 200);
        formData.append("fileName", dataOss.fileName);
        formData.append("file", params.raw);

        //this.form.contractType = this.uplodType;
        // this.form.showImgSrc=;

        let fileForm = {
          showName: imgName,
          url: dataOss.fileName,
          size: params.size,
          sid: this.id,
          type: this.uplodType
        };
        this.fileForm = fileForm;
        this.formData = formData;

        this.ossUrl = ossUrl;
      });
      await this.axios
        .post(this.ossUrl, this.formData, this.config)
        .then((res) => {
          if (res.status == 200) {
            this.form[fieldName] =
              "https://file.xssbdc.com/" +
              dataOss.dir +
              dataOss.fileName +
              "." +
              suffix;
          }
        });
    },
    async submitData() {
      //表头信息
      /* let config = {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      }; */
      if (this.imgFileList.length > 0) {
        await this.uploadToOss(this.imgFileList[0], "showImgSrc");
      }
      if (this.fileList.length > 0) {
        await this.uploadToOss(this.fileList[0], "url");
      }
      if (
        this.form.name == "" ||
        this.form.contractType == "" ||
        this.form.fileType == "" ||
        this.form.showImgSrc == "" ||
        this.form.url == ""
      ) {
        this.$message({ message: "请先完善信息", type: "error" });
        return;
      } else {
        uploadContract(this.form).then((data) => {
          if (data.code == 200) {
            this.$message({ message: data.message, type: "success" });
            this.cancelUplod();
            this.getData();
          } else {
            this.$message({ message: data.message, type: "error" });
          }
        });
      }
    },
    //取消按钮!
    cancelUplod() {
      this.$refs.uploadImg.clearFiles();
      this.$refs.uploadFile.clearFiles();
      this.dialogVisible = false;
      this.form.contractType = "";
      this.form.name = "";
      this.form.showImgSrc = "";
      this.form.url = "";
      this.form.fileType = "";
      this.fileList = [];
      this.imgFileList = [];
    },
    handleClose() {
      this.cancelUplod();
    }
  }
};
</script>
<style lang="less" scoped>
.titleStyle {
  font-size: 18px;
  font-weight: bold;
  margin-top: 13px;
  margin-bottom: 16px;
  margin-left: 20px;
  text-align: left;
}

.itemBox {
  // float: left;
  position: relative;
  width: 318px;
  height: 420px;
  margin-bottom: 20px;
  margin-left: 20px;
  border-radius: 15px;
  background-color: #f8fafb;
}

.item1box1 {
  position: absolute;
  height: 26px;
  margin-top: 19px;
  text-align: left;

  .item1span {
    font-size: 16px;
    font-weight: bold;
    position: absolute;
    top: 3px;
    left: 139px;
    display: inline-block;
    width: 100px;
  }
}

.item1box1 img {
  margin-left: 99px;
}

.item1Img {
  width: 220px;
  height: 286px;
  margin-top: 64px;
}

.buttombox {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 48px;
  border-radius: 0 0 15px 15px;
  background-color: #fff;
  // text-align: center;
}

.buttombox span {
  font-size: 14px;
  position: absolute;
  bottom: 17px;
  left: 30px;
}

.maskBox {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 372px;
  border-radius: 15px 15px 0 0;
  background: linear-gradient(rgba(0, 0, 0, .2), rgba(0, 0, 0, .2));
}

/deep/ .box1 .buttonClass {
  font-size: 16px;
  width: 180px;
  height: 50px;
  background-color: #fb575e;
}

.maskBox .box1 {
  position: absolute;
  top: 126px;
  right: 69px;
}

.maskBox .box2 {
  position: absolute;
  top: 196px;
  right: 69px;
}

// .maskBox .box1
// {
//     margin-top: 196px;
// }
// .BOX{
//   float: left;
// }
/deep/ .box2 .buttonClass {
  font-size: 16px;
  width: 180px;
  height: 50px;
}

.parentBox {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
}

.uplodItem {
  font-size: 30px;
  font-weight: bold;
  position: relative;
  cursor: pointer;
}

// .uplodItem .indexUplog img
// {
//     width: 51px; height: 51px; margin-top: 160px; margin-left: 134px;
// }
// .uplodItem .indexUplog
// {
//     width: 51px; height: 51px;
// }
.indexUplog {
  font-size: 16px;
  font-weight: bold;
  position: absolute;
  top: 243px;
  left: 126px;
  color: #999;
}

.itemBoxImg {
  position: absolute;
  top: 160px;
  left: 134px;
  width: 51px;
  height: 51px;
}

// .imgDelete
// {
//     position: absolute;  top: 15px;  right: 29px;cursor: pointer;
// }
/deep/ .deleteButton {
  position: absolute;
  top: 37px;
  right: 7px;
}

/deep/ .imgDeletes {
  position: absolute;
  top: -22px;
  right: 10px;
  width: 18px;
  height: 18px;
  border: 0;
  background-color: transparent;
  background-image: url('../../assets/img/删除 (1).png');
  background-repeat: no-repeat;
  background-size: 18px 18px;
}

// .maskBox
// {
//     display: none;
// }
// .itembOX:hover .children
// {
//     display: block;
// }


</style>
